/**
 * Project: yui3-common-hub-core
 * Class AbstractHubDataParseHandler
 * Version 1.0
 * File Created at 2020-12-17
 * $Id$
 * author yuyi
 * email 1060771195@qq.com
 */
package yui.comn.hub.data.parser.handler;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import com.fasterxml.jackson.databind.ObjectMapper;

import yui.comn.hub.model.Symbol;

/**
 * <p>
 * 抽象类
 * </p>
 *
 * @author yuyi (1060771195@qq.com)
 */
public abstract class AbstractHubDataParseHandler implements IHubDataParseHandler {
    protected final Logger log = LoggerFactory.getLogger(getClass());
    
    // protected ObjectMapper objectMapper = new ObjectMapper();
    
    @Autowired
    private MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter;
    
    public ObjectMapper getObjectMapper() {
        return mappingJackson2HttpMessageConverter.getObjectMapper();
    }
    
    @PostConstruct
    public void init() {
        HubDataParseRegister.registerHandler(getRegisterName(), this);
    }
    
    protected abstract String getRegisterName();
    
    @Override
    public Object get(Object obj, String mapper) {
        if (null == obj || StringUtils.isBlank(mapper)) {
            return null;
        }
        
        String[] attrs = StringUtils.split(mapper, Symbol.DOT);
        //先获取属性之前的对象值，比如 sysUserVo.usNm， 就是先获取sysUserVo对象
        for (int i = 0; i < attrs.length - 1; i++) {
            obj = getObjByAttr(obj, attrs[i]);
        }
        if (null == obj) {
            return null;
        }
        
        String attrName = attrs[attrs.length - 1];
        
        return getAttrValue(obj, attrName);
    }

    protected abstract Object getObjByAttr(Object obj, String attrName);
    
    protected abstract Object getAttrValue(Object obj, String attrName);

}
